<template>
    <div>
        <Button style="margin:0 10px 10px 0" type="primary" @click="modalAdd = true">添加</Button>
        <Button style="margin:0 10px 10px 0" type="error" @click="removes">删除多个</Button>
        
        <Input v-model="filter.name">
            <Button slot="append" icon="ios-search" @click="searchData"></Button>
        </Input>

        <Table ref="selection" @on-selection-change="onSelectionChangeHandler" border :columns="columns" :data="data"></Table>
        <Page :total="total" :page-size="filter.rows" :page-size-opts="[2,4,6,8,10]" @on-page-size-change="onPageSizeChangeHandler" @on-change="onChangeHandler" show-sizer></Page>
        <Modal
            v-model="modalAdd"
            title="添加信息框"
            >
            <!--在弹出框里面再加一个表单，用于添加信息的书写-->
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="评论" prop="title">
                    <Input v-model="formValidate.title" placeholder="输入评论内容"></Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
                <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
            </div>
        </Modal>
    </div>
</template>
<script>

    export default {
        data () {
            return {
                modalAdd:false,
                editId:0,
                data: [],
                total:0,
                tree: [],
                num:{
                    numb:0
                },
                filter:{
                    page:1,
                    rows:4,//每页显示几条数据
                    //name:"",
                    title:"",
                    cateId:"",
                },
                ids:[],
                formValidate: {
                    title: '',
                    cateId:"",
                },
                ruleValidate: {
                    name: [
                        { required: true, message: '评论不能为空', trigger: 'blur' }
                    ],
                },
                columns: [
                    {//单选框
                        type:'selection',
                        width:60,
                        align:'center'
                    },
                    {//用户模块中的用户姓名
                        title: '评论',
                        key: 'name',
                        render: (h, params) => {
                            return h('div', [
                                h('Icon', {
                                    props: {
                                        type: 'person'
                                    }
                                }),
                                h('strong', params.row.title)
                            ]);
                        }
                    },
                    {//用户模块中的操作（修改和删除）
                        title: '操作',
                        key: 'action',
                        width: 150,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.editData(params.row._id)
                                        }
                                    }
                                }, '修改'),
                                h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: () => {
                                            this.remove(params.row._id)//这里的params.row._id就是当前点击的用户信息的id
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    },                  
                ],
            };
        },
        methods: {
        //添加数据操作
        handleSubmit (info) {
            this.$refs[info].validate((valid) => {
                if (valid) {
                    //console.log(this.editId)
                    if(this.editId.length>0){
                        //此时是修改
                        fetch(`http://localhost:3000/comment/data/${this.editId}`,{
                            method:'put',
                            headers:{
                                'Content-Type':'application/json'
                            },
                            body:JSON.stringify(this.formValidate)
                        }).then(res=>{
                            return res.json();
                        }).then(data=>{
                            this.getData();
                            this.$Message.success('修改成功!');
                            this.modalAdd = false;     
                            this.editId = 0;
                            this.formValidate = '';                      
                        });
                        
                    }else{
                        //此时是添加
                        fetch(`http://localhost:3000/comment/data`,{
                            method:'post',
                            headers:{
                                'Content-Type':'application/json'
                            },
                            body:JSON.stringify(this.formValidate)
                        }).then(res=>{
                            return res.json();
                        }).then(data=>{
                            this.num.numb++;
                            this.getData();
                            this.$Message.success('添加成功!');
                            this.modalAdd = false;
                            // console.log(this.num.numb);
                            //更新评论的数
                            fetch(`http://localhost:3000/news/data/${this.filter.cateId}`,{
                            method:'put',
                            headers:{
                                'Content-Type':'application/json'
                            },
                            body:JSON.stringify(this.num)
                            }).then(res=>{
                                return res.json();
                            }).then(data=>{
                                //console.log(data);
                            });
                        });
                    }
                } else {
                    this.$Message.error('添加失败!');
                }
            })
        },
        handleReset (info) {
            this.$refs[info].resetFields();
        },
        editData (id) {
            fetch(`http://localhost:3000/comment/data/${id}`).then(res=>{
                return res.json();
            }).then(data=>{
                //console.log(data);
                this.formValidate = data;
                this.editId = id;
                this.modalAdd = true;
            });
        },
        //删除单条数据数据操作
        remove (id) {
            this.$Modal.confirm({
                title: '删除确认对话框',
                content: '<p>是否确认删除该条信息？</p>',
                onOk: () => {
                    fetch(`http://localhost:3000/comment/data/${id}`,{
                        method:'delete',
                    }).then(res=>{
                        return res.json();
                    }).then(data=>{
                        this.num.numb--;
                        this.$Message.info('已删除');
                        this.getData();
                        fetch(`http://localhost:3000/news/data/${this.filter.cateId}`,{
                            method:'put',
                            headers:{
                                'Content-Type':'application/json'
                            },
                            body:JSON.stringify(this.num)
                            }).then(res=>{
                                return res.json();
                            }).then(data=>{
                                //console.log(data);
                            });
                    });   
                },
                onCancel: () => {
                    this.$Message.info('已取消删除');
                }
            });
        },
        //删除多个
        removes(){
            this.$Modal.confirm({
                title: '删除确认对话框',
                content: '<p>是否确认删除选中的信息？</p>',
                onOk: () => {
                    fetch(`http://localhost:3000/comment/removes`,{
                        method:'post',
                        headers:{
                            'Content-Type':'application/json'
                        },
                        body:JSON.stringify({ids:this.ids})
                    }).then(res=>{
                        return res.json();
                    }).then(data=>{
                        this.num.numb-=this.ids.length;
                        this.$Message.info('选中的信息已删除');
                        this.getData();
                        fetch(`http://localhost:3000/news/data/${this.filter.cateId}`,{
                            method:'put',
                            headers:{
                                'Content-Type':'application/json'
                            },
                            body:JSON.stringify(this.num)
                            }).then(res=>{
                                return res.json();
                            }).then(data=>{
                                //console.log(data);
                            });
                    });   
                },
                onCancel: () => {
                    this.$Message.info('已取消删除');
                }
            });
        },
        //将选中的多个数据的id存在ids里面
        onSelectionChangeHandler(selection){
            var selectionIds = [];
            for(let i=0;i<selection.length;i++){
                selectionIds.push(selection[i]._id);
            }
            this.ids = selectionIds;
            //console.log(this.ids);
        },
        //获取用户数据
        getData(){//定义获取数据库的方法
            var bodyString= JSON.stringify(this.filter);//这里把filter里面的信息转成字符串形式存下来
            fetch(`http://localhost:3000/comment/list`,{
                method:'post',
                headers:{
                    'Content-Type':"application/json"
                },
                body:bodyString//前台定义的数据传到后台去
            }).then(res=>{
                    return res.json();
                }).then(data=>{
                    console.log(data)
                    this.data = data.rows;//这里赋值后台返回的数据。rows代表数据库里面的所有数据，total是分页里面的参数
                    this.total = data.total;
                    this.num.numb = data.total;
                    //console.log(this.numb)
                });
        },
        //分页操作
        onChangeHandler(page){
            this.filter.page = page;//获取分页参数，第几页
            this.getData();
        },
        onPageSizeChangeHandler(pageSize){
            //console.log(pageSize);
            this.filter.rows = pageSize;//获取一页显示几个
            this.getData();
        },
        //搜索功能
        searchData(){
            this.getData();
        },
        //树结构点击获取信息
    },
    created(){//钩子函数里面调用上面定义的获取数据的方法
        this.filter.cateId = this.$route.query.newsId;//在钩子函数create()里面先接收新闻组件传过来的新闻id显示相应的新闻评论
        this.formValidate.cateId = this.filter.cateId;
        this.getData();
    },
};
</script>